package cn.bonoon.services.plugins;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.IOwnerEditor;
import cn.bonoon.core.plugins.OwnerService;
import cn.bonoon.entities.AccountEntity;
import cn.bonoon.entities.AccountPrivilegeEntity;
import cn.bonoon.entities.OwnerEntity;
import cn.bonoon.entities.RoleAccountEntity;
import cn.bonoon.entities.RoleEntity;
import cn.bonoon.kernel.FlagType;
import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.menus.ModuleManager;
import cn.bonoon.kernel.support.PasswordVerifier;
import cn.bonoon.kernel.support.services.AbstractService;

@Service
@Transactional(readOnly = true)
public class OwnerServiceImpl extends AbstractService<OwnerEntity> implements OwnerService {

	private final PasswordVerifier passwordVerifier;
	private final ModuleManager moduleManager;

	@Autowired
	public OwnerServiceImpl(PasswordVerifier passwordVerifier, ModuleManager moduleManager) {
		this.passwordVerifier = passwordVerifier;
		this.moduleManager = moduleManager;
	}

	@Override
	@Transactional
	protected OwnerEntity __save(OperateEvent event, OwnerEntity entity) throws Exception{
		OwnerEntity _entity = super.__save(event, entity);

		IOwnerEditor oe = (IOwnerEditor) event.getSource();
		AccountEntity account = new AccountEntity(); // 身份不需要填,用户名就是域名,备注是域的备注,身份是管理员
		passwordVerifier.setPassword(account, oe.getLoginPwd(), oe.getConfimPwd());
		passwordVerifier.setLoginName(account, oe.getLoginName());
		account.setCreateAt(event.now());
		account.setCreatorId(event.getId());
		account.setCreatorName(event.getUsername());
		account.setOwnerId(event.getOwnerId());
		account.setName(_entity.getName());
		account.setRemark(_entity.getRemark());
		account.setExpiredAt(oe.getExpiredAt());
		account.setForcedChangePwd(oe.isForcedChangePwd());
		account.setStatus(oe.getStatus());
		account.setFlag(FlagType.ADMIN);
		entityManager.persist(account);

		Long[] roles = oe.getRoles();
		if (null != roles && roles.length != 0) {
			for (Long role : roles) {
				RoleAccountEntity rae = new RoleAccountEntity();
				rae.setAccount(account);
				rae.setRole(entityManager.find(RoleEntity.class, role));
				rae.setCreateAt(event.now());
				rae.setCreatorId(event.getId());
				entityManager.persist(rae);
			}
		}

		String[] privileges = oe.getPrivilege();
		if (null != privileges && privileges.length != 0) {
			for (String privilege : privileges) {
				AccountPrivilegeEntity ap = new AccountPrivilegeEntity();
				ap.setAccount(account);
				ap.setChannelId(moduleManager.getChannelManager().getId());
				ap.setMeunId(privilege);
				ap.setModuleId(moduleManager.getId());
				entityManager.persist(ap);
			}
		}

		return _entity;
	}

}
